const express = require('express');
const multer = require('multer');
const path = require('path');
const { body, validationResult } = require('express-validator');
const rateLimit = require('express-rate-limit');

const User = require('../models/User');
const Clue = require('../models/Clue');
const db = require('../config/database');
const { generateUUID, md5 } = require('../utils/encryption');

const router = express.Router();

// 短信验证码存储（实际项目中应使用Redis）
const smsCodeStore = new Map();

// 设置文件上传
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/');
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    const ext = path.extname(file.originalname);
    cb(null, uniqueSuffix + ext);
  }
});

const upload = multer({
  storage: storage,
  limits: {
    fileSize: process.env.MAX_FILE_SIZE || 5 * 1024 * 1024, // 5MB
    files: 4 // 最多4个文件
  },
  fileFilter: (req, file, cb) => {
    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/tiff', 'image/svg+xml',
                         'application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                         'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                         'audio/mpeg', 'video/mp4', 'video/avi', 'video/quicktime'];
    
    if (allowedTypes.includes(file.mimetype)) {
      cb(null, true);
    } else {
      cb(new Error('不支持的文件类型'), false);
    }
  }
});

// 提交频率限制
const submitLimit = rateLimit({
  windowMs: 60 * 1000, // 1分钟
  max: process.env.SUBMIT_RATE_LIMIT || 5, // 最多5次提交
  message: {
    code: 429,
    message: '提交过于频繁，请稍后再试',
    timestamp: Date.now()
  },
  standardHeaders: true,
  legacyHeaders: false,
});

// 新的举报提交验证规则
const reportValidation = [
  // Report Type: Must be present and valid
  body('reportType').notEmpty().withMessage('举报类型不能为空').isIn(['realname', 'anonymous']).withMessage('举报类型无效'),

  // Reporter Name: Required if realname report, optional if anonymous
  body('reporterName').custom((value, { req }) => {
    if (req.body.reportType === 'realname' && !value) {
      throw new Error('举报人姓名不能为空');
    }
    return true;
  }).isLength({ max: 100 }).withMessage('举报人姓名信息过长').optional({ checkFalsy: true }), // Allow null/empty if not realname

  // Reporter Phone: Required if realname report, optional if anonymous, and validate format
  body('reporterPhone').custom((value, { req }) => {
    if (req.body.reportType === 'realname' && !value) {
      throw new Error('联系方式不能为空');
    }
    if (req.body.reportType === 'realname' && value && !/^1[3-9]\d{9}$/.test(value)) {
      throw new Error('请输入正确的手机号码');
    }
    return true;
  }).isLength({ max: 100 }).withMessage('联系方式信息过长').optional({ checkFalsy: true }), // Allow null/empty if not realname

  // Reporter ID Card: Optional
  body('reporterIdCard').optional({ checkFalsy: true }).isLength({ max: 200 }).withMessage('身份证号码信息过长'),

  // Reporter Address: Optional
  body('reporterAddress').optional({ checkFalsy: true }).isLength({ max: 255 }).withMessage('详细地址信息过长'),

  // Clue Category: Always required
  body('clueCategory').notEmpty().withMessage('线索分类不能为空'),

  // Clue Content: Always required, min 200 characters
  body('clueContent').notEmpty().withMessage('举报详情不能为空'),

  // Incident Time: Always required, and valid date-time format
  body('incidentTime').notEmpty().withMessage('举报案（事）件发生时间不能为空').isISO8601().toDate().withMessage('举报案（事）件发生时间格式不正确'),

  // Incident Location: Always required
  body('incidentLocation').notEmpty().withMessage('举报案（事）件发生地点不能为空').isLength({ max: 200 }).withMessage('举报案（事）件发生地点信息过长'),

  // Involved Persons: Optional
  body('involvedPersons').optional({ checkFalsy: true }).isLength({ max: 255 }).withMessage('举报案（事）件人员的基本情况信息过长'),
  
  // Clue Title: Optional (前端页面可能不包含此字段)
  body('clueTitle').optional({ checkFalsy: true }).isLength({ max: 200 }).withMessage('线索标题信息过长'),
];

/**
 * @route POST /api/submit-clue
 * @desc 提交举报（新版本）
 * @access Public
 */
router.post('/submit-clue', submitLimit, upload.array('files', 4), (req, res, next) => {
  // 确保 reportType 字段在验证前被设置，因为前端现在是匿名举报
  if (!req.body.reportType) {
    req.body.reportType = 'anonymous';
  }
  
  // 调试：输出接收到的请求体
  console.log('📥 接收到的请求体字段:', Object.keys(req.body));
  console.log('📥 请求体内容:', req.body);
  
  next();
}, reportValidation, async (req, res) => {
  try {
    console.log('📝 收到新举报提交请求');
    
    // 验证表单数据
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      console.log('❌ 表单验证失败:', errors.array());
      return res.status(400).json({
        success: false,
        message: '表单验证失败',
        errors: errors.array()
      });
    }

    // 匿名举报不需要短信验证 (此逻辑应在前端处理，或者后端根据reportType跳过)
    const { reportType, reporterPhone, smsCode, reporterName, reporterIdCard, reporterAddress, clueCategory, clueContent, incidentTime, incidentLocation, involvedPersons } = req.body;
    console.log('Public route: reportType:', reportType, 'reporterName:', reporterName, 'reporterPhone:', reporterPhone);

    // Validate SMS code only if it's a realname report
    if (reportType === 'realname') {
      const storedCode = smsCodeStore.get(`code_${reporterPhone}`);
      
      if (!storedCode || storedCode !== smsCode) {
        return res.status(400).json({
          success: false,
          message: '验证码错误或已过期'
        });
      }

      // 验证码验证成功后删除
      smsCodeStore.delete(`code_${reporterPhone}`);
      smsCodeStore.delete(`time_${reporterPhone}`);
    }

    const clientIP = req.ip || req.connection.remoteAddress;
    const userAgent = req.get('User-Agent');

    console.log('👤 开始创建用户...');
    // 创建用户 (匿名或实名)
    const user = new User({
      name: reportType === 'anonymous' ? null : reporterName, 
      phone: reporterPhone, // 即使是匿名举报，也填充手机号
      id_card: reportType === 'anonymous' ? null : reporterIdCard, 
      province: reportType === 'anonymous' ? null : '江西省', 
      city: reportType === 'anonymous' ? null : '宜春市',   
      district: reportType === 'anonymous' ? null : '袁州区', 
      address: reportType === 'anonymous' ? null : reporterAddress, 
      is_anonymous: reportType === 'anonymous' ? 1 : 0,
      ip_address: clientIP,
      user_agent: userAgent
    });
    await user.create();
    console.log('✅ 用户创建成功, ID:', user.id);

    // 获取或创建线索分类
    let categoryId = 1; // 默认分类ID (其他)
    const categoryQuery = `
      SELECT * FROM clue_categories 
      WHERE name = ? AND is_active = 1 
      LIMIT 1
    `;
    const categoryResult = await db.query(categoryQuery, [clueCategory]);
    if (categoryResult.length > 0) {
      categoryId = categoryResult[0].id;
    }

    console.log('📋 开始创建线索...');
    // 创建线索 - 自动生成标题
    const generatedTitle = clueContent.substring(0, 50).replace(/\s+/g, ' ').trim() + (clueContent.length > 50 ? '...' : '');
    
    const clue = new Clue({
      user_id: user.id,
      category_id: categoryId,
      category: clueCategory || '其他',
      title: generatedTitle, // 自动从内容生成标题
      content: clueContent,
      suspect_info: involvedPersons || null, //涉案人员
      incident_time: incidentTime, 
      incident_location: incidentLocation 
    });
    await clue.create();
    console.log('✅ 线索创建成功, 编号:', clue.clue_no);

    // 处理文件上传
    if (req.files && req.files.length > 0) {
      console.log('📎 开始处理附件上传...');
      for (const file of req.files) {
        const attachmentQuery = `
          INSERT INTO attachments (clue_id, file_name, file_path, file_size, file_type, file_extension, upload_ip)
          VALUES (?, ?, ?, ?, ?, ?, ?)
        `;
        
        await db.query(attachmentQuery, [
          clue.id,
          file.originalname,
          file.path,
          file.size,
          file.mimetype,
          path.extname(file.originalname),
          clientIP
        ]);
      }
      console.log(`✅ 成功上传 ${req.files.length} 个附件`);
    }

    res.json({
      success: true,
      message: '举报提交成功',
      clueNo: clue.clue_no
    });

  } catch (error) {
    console.error('❌ 提交举报失败:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误，请稍后重试'
    });
  }
});

/**
 * @route POST /api/clues/:id/attachments
 * @desc 上传附件
 * @access Public
 */
router.post('/clues/:id/attachments', upload.array('files', 5), async (req, res) => {
  try {
    const clueId = parseInt(req.params.id);
    const files = req.files;

    if (!files || files.length === 0) {
      return res.status(400).json({
        code: 400,
        message: '未选择文件',
        timestamp: Date.now()
      });
    }

    // 验证线索是否存在
    const clue = await Clue.findById(clueId);
    if (!clue) {
      return res.status(404).json({
        code: 404,
        message: '线索不存在',
        timestamp: Date.now()
      });
    }

    const uploadedFiles = [];
    const clientIP = req.ip || req.connection.remoteAddress;

    for (const file of files) {
      const fileHash = md5(file.buffer || file.path);
      
      const attachmentData = {
        clue_id: clueId,
        file_name: file.originalname,
        file_path: file.path,
        file_size: file.size,
        file_type: file.mimetype,
        file_extension: path.extname(file.originalname),
        file_hash: fileHash,
        upload_ip: clientIP
      };

      const result = await db.insert('attachments', attachmentData);
      
      uploadedFiles.push({
        id: result.insertId,
        file_name: file.originalname,
        file_size: file.size,
        file_type: file.mimetype
      });
    }

    res.json({
      code: 200,
      message: '附件上传成功',
      data: {
        uploaded_files: uploadedFiles
      },
      timestamp: Date.now()
    });

  } catch (error) {
    console.error('上传附件失败:', error);
    res.status(500).json({
      code: 500,
      message: '上传失败，请稍后重试',
      timestamp: Date.now()
    });
  }
});

/**
 * @route GET /api/regions
 * @desc 获取地区列表
 * @access Public
 */
router.get('/regions', async (req, res) => {
  try {
    const { parent_id = 0 } = req.query;

    const regions = await db.findMany('regions', 
      { parent_id: parseInt(parent_id), is_active: 1 },
      { orderBy: 'sort_order ASC, id ASC' }
    );

    res.json({
      code: 200,
      message: 'success',
      data: regions,
      timestamp: Date.now()
    });

  } catch (error) {
    console.error('获取地区列表失败:', error);
    res.status(500).json({
      code: 500,
      message: '获取地区信息失败',
      timestamp: Date.now()
    });
  }
});

/**
 * @route GET /api/clue-categories
 * @desc 获取线索分类
 * @access Public
 */
router.get('/clue-categories', async (req, res) => {
  try {
    const categories = await db.findMany('clue_categories', 
      { is_active: 1 },
      { orderBy: 'sort_order ASC, id ASC' }
    );

    res.json({
      code: 200,
      message: 'success',
      data: categories.map(cat => ({
        id: cat.id,
        name: cat.name,
        code: cat.code,
        description: cat.description
      })),
      timestamp: Date.now()
    });

  } catch (error) {
    console.error('获取线索分类失败:', error);
    res.status(500).json({
      code: 500,
      message: '获取分类信息失败',
      timestamp: Date.now()
    });
  }
});

/**
 * @route GET /api/system-settings
 * @desc 获取公开的系统设置
 * @access Public
 */
router.get('/system-settings', async (req, res) => {
  try {
    const settings = await db.findMany('system_settings', { is_public: 1 });
    
    const settingsObj = {};
    settings.forEach(setting => {
      let value = setting.setting_value;
      
      // 根据类型转换值
      switch (setting.setting_type) {
        case 'number':
          value = parseFloat(value);
          break;
        case 'boolean':
          value = value === '1' || value === 'true';
          break;
        case 'json':
          try {
            value = JSON.parse(value);
          } catch (e) {
            value = setting.setting_value;
          }
          break;
      }
      
      settingsObj[setting.setting_key] = value;
    });

    res.json({
      code: 200,
      message: 'success',
      data: settingsObj,
      timestamp: Date.now()
    });

  } catch (error) {
    console.error('获取系统设置失败:', error);
    res.status(500).json({
      code: 500,
      message: '获取系统配置失败',
      timestamp: Date.now()
    });
  }
});

/**
 * @route GET /api/captcha
 * @desc 获取验证码（如果需要的话）
 * @access Public
 */
router.get('/captcha', (req, res) => {
  // 这里可以集成验证码库，如 svg-captcha
  // 暂时返回模拟数据
  const captchaId = generateUUID();
  
  res.json({
    code: 200,
    message: 'success',
    data: {
      captcha_id: captchaId,
      captcha_image: ''
    },
    timestamp: Date.now()
  });
});

/**
 * @route POST /api/verify-captcha
 * @desc 验证验证码
 * @access Public
 */
router.post('/verify-captcha', [
  body('captcha_id').notEmpty().withMessage('验证码ID不能为空'),
  body('captcha_code').notEmpty().withMessage('验证码不能为空')
], (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({
      code: 400,
      message: '验证失败',
      errors: errors.array(),
      timestamp: Date.now()
    });
  }

  // 这里应该验证验证码，暂时返回成功
  res.json({
    code: 200,
    message: '验证成功',
    timestamp: Date.now()
  });
});

module.exports = router; 